package com.service.Impl;

import com.dto.ProductRecommendationDto;
import com.entity.Category;
import com.entity.Product;
import com.exception.AddException;
import com.exception.DateNotFoundException;
import com.exception.UpdateException;
import com.github.pagehelper.PageInfo;
import com.mapper.CategoryMapper;
import com.mapper.OrderMapper;
import com.mapper.ProductMapper;
import com.service.CategoryService;
import com.service.ProductService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ClassName: ProductDaoImpl
 * Description: 商品信息接口实现类
 *
 * @Author L_Z_R
 * @Create 2025/04/16 16:30
 * @Version 1.0
 */
@Service("productService")
public class ProductServiceImpl implements ProductService {

    private final ProductMapper productMapper; // 商品持久层接口对象
    private final CategoryMapper categoryMapper; // 商品分类持久层接口对象
    private final OrderMapper orderMapper; // 订单持久层接口对象

    public ProductServiceImpl(ProductMapper productMapper, CategoryMapper categoryMapper, OrderMapper orderMapper) {
        this.productMapper = productMapper;
        this.categoryMapper = categoryMapper;
        this.orderMapper = orderMapper;
    }

    /**
     * @return java.util.List<com.entity.Product>
     * @author: kx
     * @date: 2025/5/20 20:00
     * @description: 查询所有商品信息
     */
    @Override
    public ProductRecommendationDto findAll(Integer userId, HttpServletRequest request) {
        // 获取当前项目下存储图片的路径
        String realPath = request.getServletContext().getRealPath("/images");
        // 创建传输对象
        ProductRecommendationDto productRecommendationDto = new ProductRecommendationDto();
        // 存储推荐商品
        List<Product> productList = new ArrayList<>();
        // 用户存储热销商品(过滤后的商品)
        List<Product> hotProducts = new ArrayList<>();
        // 判断是否有用户登录
        if (userId != null) {
            // 查询用户最近购买商品的五个商品编号
            List<Integer> productIds = null;
            try {
                productIds = orderMapper.findRecentPurchasedProductIds(userId);
                for (Integer productId : productIds) {
                    // 获取商品所在分类中销量最高的商品
                    Product product = productMapper.findTopRelatedProductBySales(productId);
                    // 拼接图片路劲
                    product.setMainImage(realPath + "/" + product.getMainImage());
                    // 添加到集合中
                    productList.add(product);
                }
                // 设置相关商品
                productRecommendationDto.setRelatedProducts(productList);

                // 获取所有热销商品
                List<Product> products = productMapper.findAll();

                // 过滤掉已经存在的商品
                for (Product product : products) {
                    // 判断商品编号是否已经存在
                    if (!productIds.contains(product.getProductId())) {
                        // 拼接图片路劲
                        product.setMainImage(realPath + "/" + product.getMainImage());
                        // 添加到集合中
                        hotProducts.add(product);
                    }
                }
                // 设置热销商品
                productRecommendationDto.setHotProducts(hotProducts);
            } catch (Exception e) {
                throw new DateNotFoundException(1001, "商品信息不存在");
            }
        } else {
            // 获取所有热销商品
            hotProducts = productMapper.findAll();

            for (Product product : hotProducts) {
                // 拼接图片路劲
                product.setMainImage(realPath + "/" + product.getMainImage());
            }

            // 设置热销商品
            productRecommendationDto.setHotProducts(hotProducts);
        }
        return productRecommendationDto;
    }

    /**
     * @param page : 当前页
     * @param size : 每页显示数
     * @return com.github.pagehelper.PageInfo<com.entity.Product>
     * @author: kx
     * @date: 2025/5/21 9:48
     * @description: 分页查询所有商品信息
     */
    @Override
    public PageInfo<Product> findProductsByPage(int page, int size) {
        // 判断是否查询到数据
        if (productMapper.findProductsByPage(page, size) != null) {
            return new PageInfo<>(productMapper.findProductsByPage(page, size));
        }
        throw new DateNotFoundException(1001, "商品信息不存在");
    }

    /**
     * @author: kx
     * @date: 2025/6/4 20:27
     * @param title : 商品名称
     * @return java.util.List<com.entity.Product>
     * @description: 根据商品名称模糊查询商品信息
     */
    @Override
    public List<Product> searchProductsByTitle(String title) {
        if (productMapper.searchProductsByTitle(title) != null) {
            return productMapper.searchProductsByTitle(title);
        }
        throw new DateNotFoundException(1001, "商品信息不存在");
    }

    /**
     * @author: kx
     * @date: 2025/6/4 20:37
     * @param title : 商品名称
     * @param pageNum : 当前页
     * @param pageSize : 每页显示数
     * @return com.github.pagehelper.PageInfo<com.entity.Product>
     * @description: 根据商品名称模糊分页查询商品信息
     */
    @Override
    public PageInfo<Product> searchProductsByTitleWithPagination(String title, int pageNum, int pageSize) {
        if (productMapper.searchProductsByTitleWithPagination(title, pageNum, pageSize) != null) {
            return new PageInfo<>(productMapper.searchProductsByTitleWithPagination(title, pageNum, pageSize));
        }
        throw new DateNotFoundException(1001, "商品信息不存在");
    }

    /**
     * @author: kx
     * @date: 2025/5/21 11:01
     * @param product : 商品信息
     * @param categoryId : 商品分类编号
     * @description: 添加商品信息
     */
    @Transactional
    @Override
    public void addProduct(Product product, Integer categoryId) {
        // 设置创建时间
        product.setCreateTime(new Date());
        // 添加商品
        try {
            productMapper.addProduct(product);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AddException(1002, "添加商品失败");
        }
    }

    /**
     * @author: kx
     * @date: 2025/5/21 19:42
     * @param product : 商品信息
     * @description: 修改商品信息
     */
    // 启用事务管理
    @Transactional
    @Override
    public void updateProduct(Product product) {
        try {
            productMapper.updateProduct(product);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpdateException(1003, "修改商品失败");
        }
    }

    /**
     * @author: kx
     * @date: 2025/6/8 11:13
     * @param brand : 商品品牌
     * @param categoryId : 商品分类ID
     * @return java.util.List<com.entity.Product>
     * @description: 根据商品品牌查询该品牌下的所有商品(根据销量显示)
     */
    @Override
    public List<Product> findHotProductsByBrand(String brand, Integer categoryId) {
        if (productMapper.findHotProductsByBrand(brand, categoryId) != null) {
            return productMapper.findHotProductsByBrand(brand, categoryId);
        }
        throw new DateNotFoundException(1001, "商品信息不存在");
    }

    /**
     * @author: kx
     * @date: 2025/6/15 20:41
     * @param categoryId : 商品分类ID
     * @return java.util.List<com.entity.Product>
     * @description: 根据商品分类ID查询该分类下的所有商品
     */
    @Override
    public List<Product> getGoodsByCategoryId(Integer categoryId) {
        if (productMapper.getGoodsByCategoryId(categoryId) != null) {
            return productMapper.getGoodsByCategoryId(categoryId);
        }
        throw new DateNotFoundException(1001, "商品信息不存在");
    }

    @Override
    public List<Product> findHotProducts(int limit) {
        return productMapper.findHotProduct(limit);
    }
}
